<template>
    <div class="">
        <el-dialog :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" @close="onClose" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url" :data="this.param"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span style="color: red;">仅允许导入xlsx格式文件。(下载模板之后请认真查看使用说明页面)</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="onClose">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import { getConfigKey } from '@/api/system/config'
import { downloadFileId } from '@/utils/DownloadUtils'
import { getFile } from '@/api/business/file'
export default {
    name: 'ImportFile',
    props: {
        //导入数据的请求接口（必传）
        urlName: {
            type: String,
            default: ''
        },
        // 配置模板文件id的key（必传）
        templateFileKey: {
            type: String,
            default: ''
        },
        //请求接口的参数（选传）
        param:{
            type: Object,
            default: ()=>{}
        },
    },
    data() {
        return {
            fileName: undefined,//文件名称
            fid: undefined,//对应模板文件id
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + this.urlName,
            },
            date: {},
        }
    },
    created() {
        this.getFileId()
    },
    methods: {
        //关闭弹窗
        onClose() {
            this.upload.open = false
            this.$refs.upload.clearFiles();
        },
        //根据配置获取文件id
        getFileId() {
            getConfigKey(this.templateFileKey).then(result => {
                const id = result.msg
                if (id) {
                    this.getFileById(id)
                }else{
                    this.$message.error("未找到配置模板文件")
                }
            })
        },
        //根据id获取文件信息
        getFileById(id) {
            getFile(id).then(result => {
                this.fid = result.data.id
                this.fileName = result.data.originName
            })
        },
        //打开弹窗的按钮
        onOpen() {
            this.upload.open = true
        },
        /** 下载模板操作 */
        importTemplate() {
            if (this.fid) {
                this.$modal.loading("文件正在下载，请稍候...")
                downloadFileId(this.fid, this.fileName);
                this.$modal.closeLoading()
            } else {
                this.$message.error("找不到对应的文件！")
            }

        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            if(response.code==200){
                this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;color:green;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            }else{
                this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;color:red;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            }
            this.$emit("updateList")
            this.$modal.closeLoading()
        },
        // 提交上传文件
        submitFileForm() {
            if (this.$refs.upload.uploadFiles.length > 0) {
                this.$modal.loading("正在导入数据，请稍候...")
                this.$refs.upload.submit();
            } else {
                this.$modal.msgError("请选择需要导入的文件！")
            }


        }
    }
}
</script>

<style lang="scss" scoped></style>
